package cn.virens.service.impl.sys.user;

import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import cn.virens.CacheKeys;
import cn.virens.components.page.PageParamUser;
import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.common.mapper.ExampleWrapper;
import cn.virens.database.mysql.mapper.sys.user.SysUserGroupMapper;
import cn.virens.database.mysql.model.sys.user.SysUserGroup;
import cn.virens.exception.APIException;
import cn.virens.service.inter.sys.user.SysUserGroupService;

/**
 * 用户组管理 - sys_user_group
 *
 * @author Virens
 * @since  2019-10-25
 */
@Service
public class SysUserGroupServiceImpl extends BaseServiceImpl<SysUserGroupMapper, SysUserGroup> implements SysUserGroupService {

	public SysUserGroupServiceImpl() {
		super(SysUserGroup.class);
	}

	@Override
	@Cacheable(cacheNames = CacheKeys.CACHE_GROUPS, key = "'~all'")
	public List<SysUserGroup> selectAll() {
		return mBaseMapper.selectAll();
	}

	@Override
	@CacheEvict(cacheNames = CacheKeys.CACHE_GROUPS, key = "'~all'")
	public SysUserGroup insert(SysUserGroup record) {
		return super.insert(record);
	}

	@Override
	@CacheEvict(cacheNames = CacheKeys.CACHE_GROUPS, key = "'~all'")
	public SysUserGroup update(SysUserGroup record) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andEqualTo("identity", record.getIdentity());

		if (mBaseMapper.updateByExampleSelective(record, example) <= 0) {
			throw new APIException("ERROR", "更新失败");
		} else {
			return record;
		}
	}

	@Override
	@CacheEvict(cacheNames = CacheKeys.CACHE_GROUPS, key = "'~all'")
	public int delete(String identity) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andEqualTo("identity", identity);

		return mBaseMapper.deleteByExample(example);
	}

	@Override
	protected List<?> doPageQuery(PageParamUser param) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and((criteria) -> {
			criteria.andLike("name", criteriaLike(param, "name"));
			criteria.andLike("identity", criteriaLike(param, "identity"));
		});

		return mBaseMapper.selectByExample(example);
	}
}
